<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车牌号" prop="card">
        <el-input
            v-model="queryParams.card"
            placeholder="请输入车牌号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车辆类型" prop="types">
        <el-input
            v-model="queryParams.types"
            placeholder="请输入车辆类型"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车辆品牌" prop="brand">
        <el-input
            v-model="queryParams.brand"
            placeholder="请输入车辆品牌"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-if="isAuth()"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
        >删除
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="carList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="车牌号" align="center" prop="card"/>
      <el-table-column label="车辆类型" align="center" prop="types"/>
      <el-table-column label="车辆品牌" align="center" prop="brand"/>
      <el-table-column label="创建者编号" align="center" prop="createBy"  v-if="isAuth()"/>
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新者编号" align="center" prop="updateBy"  v-if="isAuth()"/>
      <el-table-column label="更新时间" align="center" prop="updateTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-if="isAuth()">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        v-show="total>0"
        :total="total"
        v-model:current-page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @current-change="getList"
    />

    <!-- 添加或修改车辆对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="carRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="车牌号" prop="card">
          <el-input v-model="form.card" placeholder="请输入车牌号"/>
        </el-form-item>
        <el-form-item label="车辆类型" prop="types">
          <el-input v-model="form.types" placeholder="请输入车辆类型"/>
        </el-form-item>
        <el-form-item label="车辆品牌" prop="brand">
          <el-input v-model="form.brand" placeholder="请输入车辆品牌"/>
        </el-form-item>
        <el-form-item label="逻辑删除列" prop="delFlag"  v-if="isAuth()">
          <el-select v-model="form.delFlag" placeholder="请选择逻辑删除状态">
            <el-option
                v-for="dict in del_flag_options"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-divider content-position="center"  v-if="isAuth()">用户车辆明细信息</el-divider>
        <el-row :gutter="10" class="mb8"  v-if="isAuth()">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddUserCarDetails">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteUserCarDetails">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="userList" :row-class-name="rowUserCarDetailsIndex"  v-if="isAuth()"
                  @selection-change="handleUserCarDetailsSelectionChange" ref="userCarDetails">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="序号" align="center" prop="index" width="80"/>
          <el-table-column label="账号" align="center" prop="username"/>
          <el-table-column label="昵称" align="center" prop="nickName"/>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--  绑定用户  -->
    <el-dialog title="绑定用户" v-model="userListOpen" width="500px" :before-close="addUserCancel">
      <el-select v-model="currentAddUserId" placeholder="请选择需要关联的用户">
        <el-option
            v-for="dict in allUserList"
            :key="dict.username"
            :label="dict.username"
            :value="parseInt(dict.id)"
        ></el-option>
      </el-select>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addUserSubmit">确 定</el-button>
          <el-button @click="addUserCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Car">
import {listCar, getCar, delCar, addCar, updateCar} from "@/api/car";
import {getCurrentInstance, reactive, ref, toRaw, toRefs} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {isAuth, parseTime} from "@/utils/common";
import request from "@/utils/request";

const {proxy} = getCurrentInstance();

const carList = ref([]);
const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedUserCarDetails = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const userListOpen = ref(false)
const allUserList = ref([])
const currentAddUserId = ref()

const del_flag_options = [
  {
    value: 1,
    label: '已删除',
  },
  {
    value: 0,
    label: '未删除',
  }
]

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    types: null,
    brand: null,
    createBy: null,
  },
  rules: {},
});

const {queryParams, form, rules} = toRefs(data);

// 为0则发送新增请求，为1则发送更新请求
let addOrUpdateFlag = ref(null)

/** 查询车辆列表 */
function getList() {
  loading.value = true;
  listCar(queryParams.value).then(response => {
    if (response.code === 200) {
      carList.value = response.data.records;
      total.value = response.data.total;
    }
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    card: null,
    types: null,
    brand: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null
  };
  userList.value = [];
  proxy.resetForm("carRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.card);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  addOrUpdateFlag.value = 0
  title.value = "添加车辆";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _card = row.card || ids.value
  addOrUpdateFlag.value = 1
  getCar(_card).then(response => {
    form.value = response.data;
    userList.value = response.data.userList;
    open.value = true;
    title.value = "修改车辆";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["carRef"].validate(valid => {
    if (valid) {
      form.value.userList = userList.value;
      if (addOrUpdateFlag.value === 1) {
        updateCar(form.value).then(response => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        });
      } else if (addOrUpdateFlag.value === 0) {
        addCar(form.value).then(response => {
          if(response.code===200){
            ElMessage.success("新增成功");
          }
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _cards = row.card || ids.value;
  ElMessageBox.confirm('是否确认删除车辆编号为"' + _cards + '"的数据项？').then(function () {
    return delCar(_cards);
  }).then(() => {
    getList();
    ElMessage.success("删除成功");
  }).catch(() => {
  });
}

/** 用户车辆明细序号 */
function rowUserCarDetailsIndex({row, rowIndex}) {
  row.index = rowIndex + 1;
}

/** 用户车辆明细添加按钮操作 */
function handleAddUserCarDetails() {
  // 清空上一次残留的用户添加信息
  allUserList.value=[]
  currentAddUserId.value=null
  request.get('/user/listAll').then((res) => {
    if (res.code === 200) {
      let allUser=res.data
      // 过滤掉已经添加过的用户
      let result = allUser.reduce((pre, cur) => {
        if (!userList.value.some(item => item.id === cur.id)) {
          pre.push(cur)
        }
        return pre
      }, [])
      result.forEach(function (item) {
        allUserList.value.push(item);
      })
    }
  }).catch((err) => {
    console.log("err:", err);
  })
  userListOpen.value = true
}

/** 用户车辆明细删除按钮操作 */
function handleDeleteUserCarDetails() {
  if (checkedUserCarDetails.value.length == 0) {
    ElMessage.error("请先选择要删除的用户车辆明细数据");
  } else {
    const userCarDetailss = userList.value;
    const checkedUserCarDetailss = checkedUserCarDetails.value;
    userList.value = userCarDetailss.filter(function (item) {
      return checkedUserCarDetailss.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleUserCarDetailsSelectionChange(selection) {
  checkedUserCarDetails.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('yang/car/export', {
    ...queryParams.value
  }, `car_${new Date().getTime()}.xlsx`)
}

/** 确认添加用户 */
function addUserSubmit(){
  // 关闭对话框
  userListOpen.value=false
  // 当前选择的用户信息
  let chooseUser=allUserList.value.filter(item=>item.id===currentAddUserId.value)[0]
  userList.value.push(chooseUser)
}

/** 取消添加用户 */
function addUserCancel(){
  userListOpen.value=false
}

getList();
</script>
